<script setup lang="ts">
import { getProductList, getProductSearchList } from "@/api/product/product";
import router from "@/router";
import { useCounterStore } from "@/stores/counter";
import { addDateRange } from "@/utils/ruoyi";
import type { UploadFile } from "element-plus";
import { onMounted, reactive, ref, toRefs, watch } from "vue";
import { useRoute } from "vue-router";
// const state = ref("");
const route = useRoute();
interface Product {
  productId: number;
  name: string;
  price: number;
  stock: number;
  categoryId: number;
  categoryName: string;
  merchantId: number;
  merchantName: string;
  description: string;
  status: string;
  createTime: string;
  img: string;
  imgs: UploadFile[];
  pageNum?: number;
  pageSize?: number;
  value: string;
}
const data = reactive({
  queryParams: <Product>{
    pageNum: 1,
    pageSize: 5,
  },
});
const { queryParams } = toRefs(data);
const state = ref("");

interface LinkItem {
  value: string;
}
const links = ref<LinkItem[]>([]);
let timeout: ReturnType<typeof setTimeout>;
const querySearchAsync = (queryString: string, cb: (arg: any) => void) => {
  const results = queryString
    ? links.value.filter(createFilter(queryString))
    : links.value;

  clearTimeout(timeout);
  timeout = setTimeout(() => {
    cb(results);
  }, 3000 * Math.random());
};
const createFilter = (queryString: string) => {
  return (restaurant: LinkItem) => {
    return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
  };
};

const handleSelect = (item: Record<string, any>) => {
  console.log(item);
  router.push("/Search?keyword=" + item.value);
};
//搜索商品按钮
const searchProduct = () => {
  router.push("/Search?keyword=" + state.value);
  // useCounterStore().keyword = state.value;
};
watch(state, async (newValue) => {
  queryParams.value.name = newValue;
  queryParams.value.categoryName = newValue;
  await getProductSearchList(queryParams.value).then((response) => {
    links.value = response.data.rows.map((item: Product) => ({
      ...item,
      value: item.name, // 确保 value 字段存在
    }));
  });
});
onMounted(async () => {
  await getProductSearchList(queryParams.value).then((response) => {
    links.value = response.data.rows.map((item: Product) => ({
      ...item,
      value: item.name, // 确保 value 字段存在
    }));
  });
});
</script>
<template>
  <el-autocomplete
    class="search"
    v-model="state"
    :fetch-suggestions="querySearchAsync"
    placeholder="搜索商品"
    @select="handleSelect"
  >
    <template #append>
      <el-button type="primary" @click="searchProduct">搜索</el-button>
    </template>
  </el-autocomplete>
</template>
<style lang="less">
.search {
  width: 800px;
  margin: 20px;
  .el-input__inner {
    height: 50px;
  }
}
.el-input-group__append {
  background-color: #e865af;
  color: #ffffff;
}
</style>
<style lang="less">
.el-input {
  --el-input-border-color: #fd0095;
}
</style>
